<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/11 0011
 * Time: 16:33
 */

namespace Cohuna\Controllers;

use Cohuna\Models\CohunaMember;
use Cohuna\Models\CohunaPermissionRole;
use Cohuna\Paginator\PaginatorArray;

/**
 * 用户管理
 * @package Cohuna\Controllers
 */
class MemberController extends ControllerBase
{
    public function listAction()
    {
        $page = max(intval($this->request->getQuery('page')),1);
        $keyword = $this->request->getQuery('keyword');
        $condition = array('member_id > 0');
        if(empty($keyword) === false){
            $condition[0] .= ' AND (account=:keyword: OR realname=:keyword: OR email=:keyword: AND phone=:keyword: OR telephone=:keyword:)';
            $condition['bind']['keyword'] = $keyword;
        }
        $offset = ($page - 1) * self::PageSize;

        $totalCount = CohunaMember::count($condition);

        $condition['offset'] = intval($offset);
        $condition['limit'] = self::PageSize;
        $condition['order'] = 'member_id DESC';

        $list = CohunaMember::find($condition);

        $paginator = new PaginatorArray([
            'data'          => $list,
            'limit'         => self::PageSize,
            'current'       => $page,
            'total_items'   => $totalCount,
            'href'          => '/merchant/list'
        ]);
        $this->view->setVar('Model',$paginator);
    }

    public function editAction()
    {
        if($this->request->isPost()){
            $member_id = intval($this->request->getPost('member_id'));
            if($member_id > 0){
                $member = CohunaMember::findFirstByMemberId($member_id);
                if(empty($member)){
                    output_json(40001,'用户不存在');
                }
            }else{
                $member = new CohunaMember();
            }
            $password = trim($this->request->getPost('password'));
            $role_id = intval($this->request->getPost('role_id'));

        }else{
            $member_id = intval($this->request->getQuery('member_id'));
            if($member_id > 0){
                $member = CohunaMember::findFirstByMemberId($member_id);
                if(empty($member)){
                    $this->dispatcher->forward(array('controller'=>'Error','Action'=>'show0404'));
                }
            }else{
                $member = new CohunaMember();
            }
        }


        $role_list  = CohunaPermissionRole::find();
        $this->view->setVar('RoleList',$role_list);
        $this->view->setVar('Model',$member);
    }



    public function detailAction()
    {

    }
}